﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace StudentCourseSystem
{
    public static class DatabaseHelper
    {
        // SQL Server 连接字符串
        private static string connectionString = "Server=(localdb)\\MSSQLLocalDB;Database=StudentCourse3;Integrated Security=True;";

        // 执行查询，返回 DataTable
        public static DataTable ExecuteQuery(string sql, params SqlParameter[] parameters)
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(parameters);
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                }
            }
            return dt;
        }

        // 执行非查询（增删改）
        public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters)
        {
            int result = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(parameters);
                    result = cmd.ExecuteNonQuery();
                }
            }
            return result;
        }

        // 创建数据库表（如果不存在）
        public static void CreateTables()
        {
            try
            {
                // 创建用户表
                ExecuteNonQuery(@"
                    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Users' AND xtype='U')
                    CREATE TABLE Users (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        Username NVARCHAR(50) NOT NULL UNIQUE,
                        Password NVARCHAR(50) NOT NULL,
                        Role NVARCHAR(50) NOT NULL
                    )");

                // 创建学生表
                ExecuteNonQuery(@"
                    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Students' AND xtype='U')
                    CREATE TABLE Students (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        StuNo NVARCHAR(50) NOT NULL UNIQUE,
                        Name NVARCHAR(100) NOT NULL,
                        Department NVARCHAR(100)
                    )");

                // 创建课程表
                ExecuteNonQuery(@"
                    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Courses' AND xtype='U')
                    CREATE TABLE Courses (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        CourseNo NVARCHAR(50) NOT NULL UNIQUE,
                        CourseName NVARCHAR(100) NOT NULL,
                        Credit INT,
                        Year INT
                    )");

                // 创建选课表
                ExecuteNonQuery(@"
                    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Selections' AND xtype='U')
                    CREATE TABLE Selections (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        StuNo NVARCHAR(50) NOT NULL,
                        CourseNo NVARCHAR(50) NOT NULL,
                        FOREIGN KEY (StuNo) REFERENCES Students(StuNo),
                        FOREIGN KEY (CourseNo) REFERENCES Courses(CourseNo)
                    )");

                // 创建选课时间设置表
                ExecuteNonQuery(@"
                    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='SelectionPeriod' AND xtype='U')
                    CREATE TABLE SelectionPeriod (
                        Id INT IDENTITY(1,1) PRIMARY KEY,
                        StartDate DATETIME NOT NULL,
                        EndDate DATETIME NOT NULL,
                        Year INT NOT NULL
                    )");

                // 添加测试用户
                DataTable userTable = ExecuteQuery("SELECT * FROM Users WHERE Username = 'admin'");
                if (userTable.Rows.Count == 0)
                {
                    ExecuteNonQuery("INSERT INTO Users (Username, Password, Role) VALUES (@Username, @Password, @Role)",
                        new SqlParameter("@Username", "admin"),
                        new SqlParameter("@Password", "admin"),
                        new SqlParameter("@Role", "老师"));

                    // 添加测试学生用户
                    ExecuteNonQuery("INSERT INTO Users (Username, Password, Role) VALUES (@Username, @Password, @Role)",
                        new SqlParameter("@Username", "s1001"),
                        new SqlParameter("@Password", "s1001"),
                        new SqlParameter("@Role", "学生"));
                }

                // 添加默认选课时间设置
                DataTable periodTable = ExecuteQuery("SELECT * FROM SelectionPeriod");
                if (periodTable.Rows.Count == 0)
                {
                    int currentYear = DateTime.Now.Year;
                    DateTime startDate = new DateTime(currentYear, 1, 1);
                    DateTime endDate = new DateTime(currentYear, 12, 31);

                    ExecuteNonQuery("INSERT INTO SelectionPeriod (StartDate, EndDate, Year) VALUES (@StartDate, @EndDate, @Year)",
                        new SqlParameter("@StartDate", startDate),
                        new SqlParameter("@EndDate", endDate),
                        new SqlParameter("@Year", currentYear));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("创建数据库表时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 检查当前是否在选课时间内
        public static bool IsSelectionPeriodActive()
        {
            try
            {
                string sql = "SELECT TOP 1 * FROM SelectionPeriod ORDER BY Year DESC";
                DataTable dt = ExecuteQuery(sql);

                if (dt.Rows.Count > 0)
                {
                    DateTime startDate = Convert.ToDateTime(dt.Rows[0]["StartDate"]);
                    DateTime endDate = Convert.ToDateTime(dt.Rows[0]["EndDate"]);
                    DateTime now = DateTime.Now;

                    return now >= startDate && now <= endDate;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("检查选课时间时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }

        // 获取当前选课时间设置
        public static DataTable GetSelectionPeriod()
        {
            return ExecuteQuery("SELECT TOP 1 * FROM SelectionPeriod ORDER BY Year DESC");
        }
    }
    public partial class ViewStudentInfoForm : Form
    {
        private string stuNo;
        private Label lblStuNo, lblName, lblDepartment;
        private TextBox txtStuNo, txtName, txtDepartment;

        public ViewStudentInfoForm(string stuNo)
        {
            this.stuNo = stuNo;
            InitializeComponent();
            LoadStudentInfo();
        }

        private void InitializeComponent()
        {
            this.Text = "学生信息";
            this.Size = new Size(400, 300);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 学号标签和文本框
            lblStuNo = new Label { Text = "学号:", Location = new Point(30, 30), AutoSize = true };
            txtStuNo = new TextBox { Location = new Point(100, 30), Size = new Size(200, 25), ReadOnly = true };

            // 姓名标签和文本框
            lblName = new Label { Text = "姓名:", Location = new Point(30, 70), AutoSize = true };
            txtName = new TextBox { Location = new Point(100, 70), Size = new Size(200, 25), ReadOnly = true };

            // 院系标签和文本框
            lblDepartment = new Label { Text = "院系:", Location = new Point(30, 110), AutoSize = true };
            txtDepartment = new TextBox { Location = new Point(100, 110), Size = new Size(200, 25), ReadOnly = true };

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(150, 160), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                lblStuNo, txtStuNo,
                lblName, txtName,
                lblDepartment, txtDepartment,
                btnClose
            });
        }

        private void LoadStudentInfo()
        {
            try
            {
                // 从数据库加载学生信息
                DataTable dt = DatabaseHelper.ExecuteQuery(
                    "SELECT * FROM Students WHERE StuNo = @StuNo",
                    new SqlParameter("@StuNo", stuNo));

                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    txtStuNo.Text = row["StuNo"].ToString();
                    txtName.Text = row["Name"].ToString();
                    txtDepartment.Text = row["Department"].ToString();
                }
                else
                {
                    MessageBox.Show("未找到学生信息", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载学生信息失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }


    // 选课管理表单
    public partial class ManageSelectionForm : Form
    {
        private DataGridView dgvSelections;
        private Button btnExportAll;

        public ManageSelectionForm()
        {
            InitializeComponent();
            LoadSelections();
        }

        private void InitializeComponent()
        {
            this.Text = "选课管理";
            this.Size = new Size(900, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 数据网格视图
            dgvSelections = new DataGridView
            {
                Location = new Point(10, 10),
                Size = new Size(880, 500),
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            // 刷新按钮
            Button btnRefresh = new Button { Text = "刷新", Location = new Point(100, 520), Size = new Size(75, 30) };
            btnRefresh.Click += (sender, e) => LoadSelections();

            // 导出按钮
            btnExportAll = new Button { Text = "导出课表", Location = new Point(200, 520), Size = new Size(100, 30) };
            btnExportAll.Click += BtnExportAll_Click;

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(700, 520), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] { dgvSelections, btnRefresh, btnExportAll, btnClose });
        }

        private void LoadSelections()
        {
            try
            {
                string sql = @"
                    SELECT 
                        s.StuNo AS 学号,
                        st.Name AS 姓名,
                        c.CourseNo AS 课程编号,
                        c.CourseName AS 课程名称,
                        c.Credit AS 学分,
                        c.Year AS 年份
                    FROM Selections s
                    JOIN Students st ON s.StuNo = st.StuNo
                    JOIN Courses c ON s.CourseNo = c.CourseNo";

                DataTable dt = DatabaseHelper.ExecuteQuery(sql);
                dgvSelections.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载选课数据失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnExportAll_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "CSV 文件 (*.csv)|*.csv";
                saveFileDialog.Title = "导出选课数据";
                saveFileDialog.FileName = $"选课数据_{DateTime.Now:yyyyMMdd}.csv";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    StringBuilder csvContent = new StringBuilder();
                    DataTable dt = (DataTable)dgvSelections.DataSource;

                    // 添加列标题
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        csvContent.Append(dt.Columns[i].ColumnName);
                        if (i < dt.Columns.Count - 1)
                            csvContent.Append(",");
                    }
                    csvContent.AppendLine();

                    // 添加数据行
                    foreach (DataRow row in dt.Rows)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            string value = row[i].ToString().Replace(",", ";");
                            csvContent.Append(value);
                            if (i < dt.Columns.Count - 1)
                                csvContent.Append(",");
                        }
                        csvContent.AppendLine();
                    }

                    File.WriteAllText(saveFileDialog.FileName, csvContent.ToString(), Encoding.UTF8);
                    MessageBox.Show("数据导出成功！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出数据时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 选课时间设置表单
    public partial class SelectionPeriodForm : Form
    {
        private DateTimePicker dtpStartDate;
        private DateTimePicker dtpEndDate;
        private TextBox txtYear;

        public SelectionPeriodForm()
        {
            InitializeComponent();
            LoadSelectionPeriod();
        }

        private void InitializeComponent()
        {
            this.Text = "选课时间设置";
            this.Size = new Size(400, 250);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 年份标签和文本框
            Label lblYear = new Label { Text = "年份:", Location = new Point(30, 30), AutoSize = true };
            txtYear = new TextBox { Location = new Point(100, 30), Size = new Size(200, 25) };

            // 开始日期标签和选择器
            Label lblStartDate = new Label { Text = "开始日期:", Location = new Point(30, 70), AutoSize = true };
            dtpStartDate = new DateTimePicker { Location = new Point(100, 70), Size = new Size(200, 25) };

            // 结束日期标签和选择器
            Label lblEndDate = new Label { Text = "结束日期:", Location = new Point(30, 110), AutoSize = true };
            dtpEndDate = new DateTimePicker { Location = new Point(100, 110), Size = new Size(200, 25) };

            // 保存按钮
            Button btnSave = new Button { Text = "保存", Location = new Point(100, 160), Size = new Size(75, 30) };
            btnSave.Click += BtnSave_Click;

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(200, 160), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                lblYear, txtYear,
                lblStartDate, dtpStartDate,
                lblEndDate, dtpEndDate,
                btnSave, btnClose
            });
        }

        private void LoadSelectionPeriod()
        {
            try
            {
                DataTable dt = DatabaseHelper.GetSelectionPeriod();
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    txtYear.Text = row["Year"].ToString();
                    dtpStartDate.Value = Convert.ToDateTime(row["StartDate"]);
                    dtpEndDate.Value = Convert.ToDateTime(row["EndDate"]);
                }
                else
                {
                    int currentYear = DateTime.Now.Year;
                    txtYear.Text = currentYear.ToString();
                    dtpStartDate.Value = new DateTime(currentYear, 1, 1);
                    dtpEndDate.Value = new DateTime(currentYear, 12, 31);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载选课时间设置失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!int.TryParse(txtYear.Text, out int year))
                {
                    MessageBox.Show("年份必须为整数", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (dtpStartDate.Value >= dtpEndDate.Value)
                {
                    MessageBox.Show("开始日期必须小于结束日期", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 先删除旧记录
                DatabaseHelper.ExecuteNonQuery("DELETE FROM SelectionPeriod WHERE Year = @Year",
                    new SqlParameter("@Year", year));

                // 插入新记录
                DatabaseHelper.ExecuteNonQuery(
                    "INSERT INTO SelectionPeriod (StartDate, EndDate, Year) VALUES (@StartDate, @EndDate, @Year)",
                    new SqlParameter("@StartDate", dtpStartDate.Value),
                    new SqlParameter("@EndDate", dtpEndDate.Value),
                    new SqlParameter("@Year", year));

                MessageBox.Show("选课时间设置保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存选课时间设置失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 选课表单 - 添加选课时间检查
    public partial class SelectCourseForm : Form
    {
        private string stuNo;
        private DataGridView dgvCourses;
        private Button btnSubmit;

        public SelectCourseForm(string stuNo)
        {
            this.stuNo = stuNo;
            InitializeComponent();
            LoadAvailableCourses();
        }

        private void InitializeComponent()
        {
            this.Text = "选课系统";
            this.Size = new Size(600, 400);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 检查选课时间
            if (!DatabaseHelper.IsSelectionPeriodActive())
            {
                MessageBox.Show("当前不在选课时间内，无法进行选课操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.Close();
                return;
            }

            // 数据网格视图
            dgvCourses = new DataGridView
            {
                Location = new Point(10, 10),
                Size = new Size(580, 300),
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = true
            };

            // 提交按钮
            btnSubmit = new Button { Text = "提交选课", Location = new Point(250, 320), Size = new Size(100, 30) };
            btnSubmit.Click += BtnSubmit_Click;

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(360, 320), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                dgvCourses, btnSubmit, btnClose
            });
        }

        private void LoadAvailableCourses()
        {
            try
            {
                int currentYear = DateTime.Now.Year;

                // 从数据库加载可选课程
                string sql = @"
                    SELECT c.* 
                    FROM Courses c
                    WHERE c.CourseNo NOT IN (
                        SELECT CourseNo FROM Selections WHERE StuNo = @StuNo
                    )
                    AND c.Year = @Year";

                DataTable dt = DatabaseHelper.ExecuteQuery(sql,
                    new SqlParameter("@StuNo", stuNo),
                    new SqlParameter("@Year", currentYear));

                dgvCourses.DataSource = dt;

                // 添加选择列
                DataGridViewCheckBoxColumn chkCol = new DataGridViewCheckBoxColumn
                {
                    HeaderText = "选择",
                    Name = "Select"
                };
                dgvCourses.Columns.Insert(0, chkCol);
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载可选课程失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                int count = 0;
                foreach (DataGridViewRow row in dgvCourses.Rows)
                {
                    if (row.Cells["Select"].Value != null &&
                        Convert.ToBoolean(row.Cells["Select"].Value) == true)
                    {
                        string courseNo = row.Cells["CourseNo"].Value.ToString();

                        // 插入选课记录
                        DatabaseHelper.ExecuteNonQuery(
                            "INSERT INTO Selections (StuNo, CourseNo) VALUES (@StuNo, @CourseNo)",
                            new SqlParameter("@StuNo", stuNo),
                            new SqlParameter("@CourseNo", courseNo));

                        count++;
                    }
                }

                MessageBox.Show($"成功选择 {count} 门课程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("选课失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 查看已选课程表单
    public partial class ViewSelectionForm : Form
    {
        private string stuNo;
        private DataGridView dgvSelections;
        private Button btnExport;

        public ViewSelectionForm(string stuNo)
        {
            this.stuNo = stuNo;
            InitializeComponent();
            LoadSelectedCourses();
        }

        private void InitializeComponent()
        {
            this.Text = "已选课程";
            this.Size = new Size(600, 400);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 数据网格视图
            dgvSelections = new DataGridView
            {
                Location = new Point(10, 10),
                Size = new Size(580, 300),
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            // 导出按钮
            btnExport = new Button { Text = "导出课表", Location = new Point(200, 320), Size = new Size(100, 30) };
            btnExport.Click += BtnExport_Click;

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(320, 320), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] { dgvSelections, btnExport, btnClose });
        }

        private void LoadSelectedCourses()
        {
            try
            {
                // 从数据库加载已选课程
                string sql = @"
                    SELECT c.CourseNo AS 课程编号, c.CourseName AS 课程名称, c.Credit AS 学分, c.Year AS 年份
                    FROM Selections s
                    JOIN Courses c ON s.CourseNo = c.CourseNo
                    WHERE s.StuNo = @StuNo";

                DataTable dt = DatabaseHelper.ExecuteQuery(sql, new SqlParameter("@StuNo", stuNo));
                dgvSelections.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载已选课程失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnExport_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "CSV 文件 (*.csv)|*.csv";
                saveFileDialog.Title = "导出课表";

                // 获取学生信息
                DataTable studentInfo = DatabaseHelper.ExecuteQuery(
                    "SELECT * FROM Students WHERE StuNo = @StuNo",
                    new SqlParameter("@StuNo", stuNo));

                string studentName = studentInfo.Rows.Count > 0 ? studentInfo.Rows[0]["Name"].ToString() : "未知";
                saveFileDialog.FileName = $"{studentName}_{stuNo}_课表_{DateTime.Now:yyyyMMdd}.csv";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    StringBuilder csvContent = new StringBuilder();
                    DataTable dt = (DataTable)dgvSelections.DataSource;

                    // 添加标题
                    csvContent.AppendLine($"学生姓名: {studentName}");
                    csvContent.AppendLine($"学号: {stuNo}");
                    csvContent.AppendLine("课表信息:");
                    csvContent.AppendLine();

                    // 添加列标题
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        csvContent.Append(dt.Columns[i].ColumnName);
                        if (i < dt.Columns.Count - 1)
                            csvContent.Append(",");
                    }
                    csvContent.AppendLine();

                    // 添加数据行
                    foreach (DataRow row in dt.Rows)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            string value = row[i].ToString().Replace(",", ";");
                            csvContent.Append(value);
                            if (i < dt.Columns.Count - 1)
                                csvContent.Append(",");
                        }
                        csvContent.AppendLine();
                    }

                    File.WriteAllText(saveFileDialog.FileName, csvContent.ToString(), Encoding.UTF8);
                    MessageBox.Show("课表导出成功！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出课表时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 退课表单 - 添加选课时间检查
    public partial class DropCourseForm : Form
    {
        private string stuNo;
        private DataGridView dgvCourses;
        private Button btnSubmit;

        public DropCourseForm(string stuNo)
        {
            this.stuNo = stuNo;
            InitializeComponent();
            LoadSelectedCourses();
        }

        private void InitializeComponent()
        {
            this.Text = "退课系统";
            this.Size = new Size(600, 400);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 检查选课时间
            if (!DatabaseHelper.IsSelectionPeriodActive())
            {
                MessageBox.Show("当前不在选课时间内，无法进行退课操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.Close();
                return;
            }

            // 数据网格视图
            dgvCourses = new DataGridView
            {
                Location = new Point(10, 10),
                Size = new Size(580, 300),
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = true
            };

            // 提交按钮
            btnSubmit = new Button { Text = "提交退课", Location = new Point(250, 320), Size = new Size(100, 30) };
            btnSubmit.Click += BtnSubmit_Click;

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(360, 320), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                dgvCourses, btnSubmit, btnClose
            });
        }

        private void LoadSelectedCourses()
        {
            try
            {
                // 从数据库加载已选课程
                string sql = @"
                    SELECT c.CourseNo, c.CourseName, c.Credit, c.Year
                    FROM Selections s
                    JOIN Courses c ON s.CourseNo = c.CourseNo
                    WHERE s.StuNo = @StuNo";

                DataTable dt = DatabaseHelper.ExecuteQuery(sql, new SqlParameter("@StuNo", stuNo));
                dgvCourses.DataSource = dt;

                // 添加选择列
                DataGridViewCheckBoxColumn chkCol = new DataGridViewCheckBoxColumn
                {
                    HeaderText = "选择",
                    Name = "Select"
                };
                dgvCourses.Columns.Insert(0, chkCol);
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载已选课程失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                int count = 0;
                foreach (DataGridViewRow row in dgvCourses.Rows)
                {
                    if (row.Cells["Select"].Value != null &&
                        Convert.ToBoolean(row.Cells["Select"].Value) == true)
                    {
                        string courseNo = row.Cells["CourseNo"].Value.ToString();
                        string courseName = row.Cells["CourseName"].Value.ToString();

                        // 确认是否退课
                        DialogResult result = MessageBox.Show($"确定要退选课程 {courseName} 吗？", "确认",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                        if (result == DialogResult.Yes)
                        {
                            // 从选课表中删除记录
                            DatabaseHelper.ExecuteNonQuery(
                                "DELETE FROM Selections WHERE StuNo = @StuNo AND CourseNo = @CourseNo",
                                new SqlParameter("@StuNo", stuNo),
                                new SqlParameter("@CourseNo", courseNo));

                            count++;
                        }
                    }
                }

                if (count > 0)
                {
                    MessageBox.Show($"成功退选 {count} 门课程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                else
                {
                    MessageBox.Show("未选择任何课程进行退选", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("退课失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 统计分析表单
    public partial class StatisticsForm : Form
    {
        private ComboBox cboYear;
        private ComboBox cboAnalysisType;
        private DataGridView dgvResults;
        private Button btnGenerate;
        private Button btnExport;

        public StatisticsForm()
        {
            InitializeComponent();
            LoadYears();
        }

        private void InitializeComponent()
        {
            this.Text = "选课统计分析";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 年份选择
            Label lblYear = new Label { Text = "年份:", Location = new Point(30, 30), AutoSize = true };
            cboYear = new ComboBox { Location = new Point(80, 30), Size = new Size(150, 25), DropDownStyle = ComboBoxStyle.DropDownList };

            // 分析类型选择
            Label lblType = new Label { Text = "分析类型:", Location = new Point(250, 30), AutoSize = true };
            cboAnalysisType = new ComboBox { Location = new Point(320, 30), Size = new Size(200, 25), DropDownStyle = ComboBoxStyle.DropDownList };
            cboAnalysisType.Items.AddRange(new string[] { "按课程统计选课人数", "按学生统计选课情况" });
            cboAnalysisType.SelectedIndex = 0;

            // 生成按钮
            btnGenerate = new Button { Text = "生成报告", Location = new Point(550, 30), Size = new Size(100, 25) };
            btnGenerate.Click += BtnGenerate_Click;

            // 数据网格视图
            dgvResults = new DataGridView
            {
                Location = new Point(10, 70),
                Size = new Size(780, 450),
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            // 导出按钮
            btnExport = new Button { Text = "导出数据", Location = new Point(350, 530), Size = new Size(100, 30) };
            btnExport.Click += BtnExport_Click;
            btnExport.Enabled = false;

            // 关闭按钮
            Button btnClose = new Button { Text = "关闭", Location = new Point(470, 530), Size = new Size(100, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                lblYear, cboYear,
                lblType, cboAnalysisType,
                btnGenerate,
                dgvResults,
                btnExport, btnClose
            });
        }

        private void LoadYears()
        {
            try
            {
                // 获取所有有选课的年份
                string sql = "SELECT DISTINCT Year FROM Courses ORDER BY Year DESC";
                DataTable dt = DatabaseHelper.ExecuteQuery(sql);

                foreach (DataRow row in dt.Rows)
                {
                    cboYear.Items.Add(row["Year"]);
                }

                if (cboYear.Items.Count > 0)
                    cboYear.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载年份数据失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnGenerate_Click(object sender, EventArgs e)
        {
            if (cboYear.SelectedItem == null || cboAnalysisType.SelectedItem == null)
            {
                MessageBox.Show("请选择年份和分析类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int year = Convert.ToInt32(cboYear.SelectedItem);
            string analysisType = cboAnalysisType.SelectedItem.ToString();

            try
            {
                DataTable dt = null;
                if (analysisType == "按课程统计选课人数")
                {
                    dt = DatabaseHelper.ExecuteQuery(@"
                        SELECT 
                            c.CourseNo AS 课程编号,
                            c.CourseName AS 课程名称,
                            COUNT(s.StuNo) AS 选课人数,
                            STRING_AGG(st.Name, ', ') WITHIN GROUP (ORDER BY st.Name) AS 学生名单
                        FROM Courses c
                        LEFT JOIN Selections s ON c.CourseNo = s.CourseNo
                        LEFT JOIN Students st ON s.StuNo = st.StuNo
                        WHERE c.Year = @Year
                        GROUP BY c.CourseNo, c.CourseName",
                        new SqlParameter("@Year", year));
                }
                else
                {
                    dt = DatabaseHelper.ExecuteQuery(@"
                        SELECT 
                            st.StuNo AS 学号,
                            st.Name AS 姓名,
                            COUNT(s.CourseNo) AS 选课数量,
                            STRING_AGG(c.CourseName, ', ') WITHIN GROUP (ORDER BY c.CourseName) AS 课程列表
                        FROM Students st
                        LEFT JOIN Selections s ON st.StuNo = s.StuNo
                        LEFT JOIN Courses c ON s.CourseNo = c.CourseNo AND c.Year = @Year
                        GROUP BY st.StuNo, st.Name",
                        new SqlParameter("@Year", year));
                }

                dgvResults.DataSource = dt;
                btnExport.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("生成报告失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnExport_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "CSV 文件 (*.csv)|*.csv";
                saveFileDialog.Title = "导出分析数据";
                saveFileDialog.FileName = $"选课分析_{cboYear.SelectedItem}_{DateTime.Now:yyyyMMdd}.csv";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    StringBuilder csvContent = new StringBuilder();
                    DataTable dt = (DataTable)dgvResults.DataSource;

                    // 添加标题
                    csvContent.AppendLine($"选课分析报告 - {cboYear.SelectedItem}年");
                    csvContent.AppendLine($"分析类型: {cboAnalysisType.SelectedItem}");
                    csvContent.AppendLine();

                    // 添加列标题
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        csvContent.Append(dt.Columns[i].ColumnName);
                        if (i < dt.Columns.Count - 1)
                            csvContent.Append(",");
                    }
                    csvContent.AppendLine();

                    // 添加数据行
                    foreach (DataRow row in dt.Rows)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            string value = row[i].ToString().Replace(",", ";");
                            csvContent.Append(value);
                            if (i < dt.Columns.Count - 1)
                                csvContent.Append(",");
                        }
                        csvContent.AppendLine();
                    }

                    File.WriteAllText(saveFileDialog.FileName, csvContent.ToString(), Encoding.UTF8);
                    MessageBox.Show("数据导出成功！", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出数据时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 登录表单（保持不变）
    // ...
    public partial class LoginForm : Form
    {
        private TextBox txtUsername;
        private TextBox txtPassword;
        private ComboBox cboRole;

        public LoginForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            // 窗体基本设置
            this.Text = "学生选课系统 - 登录";
            this.ClientSize = new Size(400, 250);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.AutoScaleMode = AutoScaleMode.Font;
            this.Padding = new Padding(20);

            // 主布局面板
            TableLayoutPanel mainPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 4,
                AutoSize = true,
                AutoSizeMode = AutoSizeMode.GrowAndShrink
            };

            // 设置列宽
            mainPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
            mainPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 70F));

            // 设置行高
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40F));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40F));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40F));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));

            // 用户名控件
            Label lblUsername = new Label
            {
                Text = "用户名:",
                TextAlign = ContentAlignment.MiddleRight,
                Dock = DockStyle.Fill
            };

            txtUsername = new TextBox
            {
                Dock = DockStyle.Fill,
                Margin = new Padding(5)
            };

            // 密码控件
            Label lblPassword = new Label
            {
                Text = "密码:",
                TextAlign = ContentAlignment.MiddleRight,
                Dock = DockStyle.Fill
            };

            txtPassword = new TextBox
            {
                Dock = DockStyle.Fill,
                Margin = new Padding(5),
                PasswordChar = '*'
            };

            // 角色控件
            Label lblRole = new Label
            {
                Text = "角色:",
                TextAlign = ContentAlignment.MiddleRight,
                Dock = DockStyle.Fill
            };

            cboRole = new ComboBox
            {
                Dock = DockStyle.Fill,
                Margin = new Padding(5)
            };
            cboRole.Items.AddRange(new string[] { "老师", "学生" });
            cboRole.SelectedIndex = 0;

            // 按钮面板
            Panel buttonPanel = new Panel
            {
                Dock = DockStyle.Fill,
                AutoSize = true
            };

            FlowLayoutPanel flowPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.RightToLeft,
                AutoSize = true,
                Padding = new Padding(0, 10, 0, 0)
            };

            Button btnCancel = new Button
            {
                Text = "取消",
                Size = new Size(80, 30),
                Margin = new Padding(5)
            };
            btnCancel.Click += (sender, e) => this.Close();

            Button btnLogin = new Button
            {
                Text = "登录",
                Size = new Size(80, 30),
                Margin = new Padding(5)
            };
            btnLogin.Click += BtnLogin_Click;

            flowPanel.Controls.Add(btnCancel);
            flowPanel.Controls.Add(btnLogin);
            buttonPanel.Controls.Add(flowPanel);

            // 添加控件到主面板
            mainPanel.Controls.Add(lblUsername, 0, 0);
            mainPanel.Controls.Add(txtUsername, 1, 0);
            mainPanel.Controls.Add(lblPassword, 0, 1);
            mainPanel.Controls.Add(txtPassword, 1, 1);
            mainPanel.Controls.Add(lblRole, 0, 2);
            mainPanel.Controls.Add(cboRole, 1, 2);
            mainPanel.Controls.Add(buttonPanel, 0, 3);
            mainPanel.SetColumnSpan(buttonPanel, 2);

            this.Controls.Add(mainPanel);
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();
            string role = cboRole.SelectedItem.ToString();

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("用户名和密码不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // 从数据库验证用户
                DataTable userTable = DatabaseHelper.ExecuteQuery(
                    "SELECT * FROM Users WHERE Username = @Username AND Password = @Password AND Role = @Role",
                    new SqlParameter("@Username", username),
                    new SqlParameter("@Password", password),
                    new SqlParameter("@Role", role));

                if (userTable.Rows.Count > 0)
                {
                    MessageBox.Show("登录成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    if (role == "老师")
                    {
                        new TeacherMainForm().Show();
                    }
                    else
                    {
                        new StudentMainForm(username).Show();
                    }

                    this.Hide();
                }
                else
                {
                    MessageBox.Show("用户名、密码或角色错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("登录时发生错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 教师主界面 - 添加新功能菜单
    public partial class TeacherMainForm : Form
    {
        public TeacherMainForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "教师管理系统";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 菜单
            MenuStrip menuStrip = new MenuStrip();

            // 学生管理菜单
            ToolStripMenuItem tsmiStudent = new ToolStripMenuItem("学生管理");
            tsmiStudent.DropDownItems.Add("添加学生", null, (sender, e) => new AddStudentForm().ShowDialog());
            tsmiStudent.DropDownItems.Add("管理学生", null, (sender, e) => new ManageStudentForm().ShowDialog());

            // 课程管理菜单
            ToolStripMenuItem tsmiCourse = new ToolStripMenuItem("课程管理");
            tsmiCourse.DropDownItems.Add("添加课程", null, (sender, e) => new AddCourseForm().ShowDialog());
            tsmiCourse.DropDownItems.Add("管理课程", null, (sender, e) => new ManageCourseForm().ShowDialog());

            // 选课管理菜单
            ToolStripMenuItem tsmiSelection = new ToolStripMenuItem("选课管理");
            tsmiSelection.DropDownItems.Add("查看选课情况", null, (sender, e) => new ManageSelectionForm().ShowDialog());

            // 统计分析菜单
            ToolStripMenuItem tsmiAnalysis = new ToolStripMenuItem("统计分析");
            tsmiAnalysis.DropDownItems.Add("选课统计", null, (sender, e) => new StatisticsForm().ShowDialog());

            // 系统设置菜单
            ToolStripMenuItem tsmiSettings = new ToolStripMenuItem("系统设置");
            tsmiSettings.DropDownItems.Add("选课时间设置", null, (sender, e) => new SelectionPeriodForm().ShowDialog());

            // 退出系统菜单
            ToolStripMenuItem tsmiExit = new ToolStripMenuItem("退出系统");
            tsmiExit.Click += (sender, e) => Application.Exit();

            // 添加所有菜单项
            menuStrip.Items.AddRange(new ToolStripItem[] {
                tsmiStudent, tsmiCourse, tsmiSelection,
                tsmiAnalysis, tsmiSettings, tsmiExit
            });

            this.MainMenuStrip = menuStrip;
            this.Controls.Add(menuStrip);
        }
    }

    // 学生主界面（保持不变）
    // ...

    public partial class StudentMainForm : Form
    {
        private string stuNo;

        public StudentMainForm(string stuNo)
        {
            this.stuNo = stuNo;
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "学生选课系统";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 菜单
            MenuStrip menuStrip = new MenuStrip();
            ToolStripMenuItem tsmiInfo = new ToolStripMenuItem("个人信息");
            ToolStripMenuItem tsmiCourse = new ToolStripMenuItem("课程管理");
            ToolStripMenuItem tsmiExit = new ToolStripMenuItem("退出系统");
            // 在InitializeComponent方法中的课程管理菜单部分添加
            tsmiCourse.DropDownItems.Add("选课", null, (sender, e) => new SelectCourseForm(stuNo).ShowDialog());
            tsmiCourse.DropDownItems.Add("查看已选课程", null, (sender, e) => new ViewSelectionForm(stuNo).ShowDialog());
            tsmiCourse.DropDownItems.Add("退课", null, (sender, e) => new DropCourseForm(stuNo).ShowDialog());

            menuStrip.Items.AddRange(new ToolStripItem[] { tsmiInfo, tsmiCourse, tsmiExit });
            this.MainMenuStrip = menuStrip;
            this.Controls.Add(menuStrip);

            // 个人信息
            tsmiInfo.DropDownItems.Add("查看信息", null, (sender, e) => new ViewStudentInfoForm(stuNo).ShowDialog());

            // 退出系统
            tsmiExit.Click += (sender, e) => Application.Exit();
        }
    }

    // 添加学生表单（保持不变）

    // ...

    public partial class AddStudentForm : Form
    {
        public AddStudentForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            // 窗体基本设置
            this.Text = "添加学生";
            this.ClientSize = new Size(400, 250); // 适当增大窗体
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Font = new Font("Microsoft YaHei", 10F); // 统一字体
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 学号标签和文本框
            Label lblStuNo = new Label
            {
                Text = "学号:",
                Location = new Point(30, 30),
                Size = new Size(80, 25), // 固定标签宽度
                TextAlign = ContentAlignment.MiddleRight // 右对齐
            };

            TextBox txtStuNo = new TextBox
            {
                Location = new Point(120, 30),
                Size = new Size(200, 30) // 增大文本框高度
            };

            // 姓名标签和文本框
            Label lblName = new Label
            {
                Text = "姓名:",
                Location = new Point(30, 70),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtName = new TextBox
            {
                Location = new Point(120, 70),
                Size = new Size(200, 30)
            };

            // 院系标签和文本框
            Label lblDepartment = new Label
            {
                Text = "院系:",
                Location = new Point(30, 110),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtDepartment = new TextBox
            {
                Location = new Point(120, 110),
                Size = new Size(200, 30)
            };

            // 保存按钮
            Button btnSave = new Button
            {
                Text = "保存",
                Location = new Point(120, 160),
                Size = new Size(80, 35) // 增大按钮尺寸
            };

            btnSave.Click += (sender, e) =>
            {
                string stuNo = txtStuNo.Text.Trim();
                string name = txtName.Text.Trim();
                string department = txtDepartment.Text.Trim();

                if (string.IsNullOrEmpty(stuNo) || string.IsNullOrEmpty(name))
                {
                    MessageBox.Show("学号和姓名不能为空", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    // 添加到学生表
                    DatabaseHelper.ExecuteNonQuery(
                        "INSERT INTO Students (StuNo, Name, Department) VALUES (@StuNo, @Name, @Department)",
                        new SqlParameter("@StuNo", stuNo),
                        new SqlParameter("@Name", name),
                        new SqlParameter("@Department", department));

                    // 同时添加到用户表
                    DatabaseHelper.ExecuteNonQuery(
                        "INSERT INTO Users (Username, Password, Role) VALUES (@Username, @Password, @Role)",
                        new SqlParameter("@Username", stuNo),
                        new SqlParameter("@Password", stuNo),
                        new SqlParameter("@Role", "学生"));

                    MessageBox.Show("学生添加成功", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("添加学生失败: " + ex.Message, "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            // 取消按钮
            Button btnCancel = new Button
            {
                Text = "取消",
                Location = new Point(220, 160),
                Size = new Size(80, 35)
            };

            btnCancel.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
            lblStuNo, txtStuNo,
            lblName, txtName,
            lblDepartment, txtDepartment,
            btnSave, btnCancel
        });
        }
    }

    // 管理学生表单 - 添加模糊查询功能
    public partial class ManageStudentForm : Form
    {
        private DataGridView dgvStudents;
        private TextBox txtSearch;
        private Button btnSearch;

        public ManageStudentForm()
        {
            InitializeComponent();
            LoadStudents();
        }

        private void InitializeComponent()
        {
            this.Text = "管理学生";
            this.Size = new Size(700, 500);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 搜索面板
            Panel searchPanel = new Panel
            {
                Location = new Point(10, 10),
                Size = new Size(680, 40)
            };

            Label lblSearch = new Label { Text = "搜索:", Location = new Point(10, 10), AutoSize = true };
            txtSearch = new TextBox { Location = new Point(60, 10), Size = new Size(300, 25) };
            btnSearch = new Button { Text = "查询", Location = new Point(370, 10), Size = new Size(75, 25) };
            btnSearch.Click += (sender, e) => LoadStudents();

            searchPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, btnSearch });

            // 数据网格视图
            dgvStudents = new DataGridView
            {
                Location = new Point(10, 60),
                Size = new Size(680, 350),
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            // 按钮
            Button btnAdd = new Button { Text = "添加", Location = new Point(100, 420), Size = new Size(75, 30) };
            btnAdd.Click += (sender, e) => { new AddStudentForm().ShowDialog(); LoadStudents(); };

            Button btnEdit = new Button { Text = "编辑", Location = new Point(200, 420), Size = new Size(75, 30) };
            btnEdit.Click += (sender, e) =>
            {
                if (dgvStudents.SelectedRows.Count > 0)
                {
                    string stuNo = dgvStudents.SelectedRows[0].Cells["学号"].Value.ToString();
                    new EditStudentForm(stuNo).ShowDialog();
                    LoadStudents();
                }
                else
                {
                    MessageBox.Show("请选择要编辑的学生", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            };

            Button btnDelete = new Button { Text = "删除", Location = new Point(300, 420), Size = new Size(75, 30) };
            btnDelete.Click += (sender, e) =>
            {
                if (dgvStudents.SelectedRows.Count > 0)
                {
                    string stuNo = dgvStudents.SelectedRows[0].Cells["学号"].Value.ToString();
                    string name = dgvStudents.SelectedRows[0].Cells["姓名"].Value.ToString();

                    if (MessageBox.Show($"确定要删除学生 {name} 吗？", "确认",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            DatabaseHelper.ExecuteNonQuery("DELETE FROM Selections WHERE StuNo = @StuNo",
                                new SqlParameter("@StuNo", stuNo));

                            DatabaseHelper.ExecuteNonQuery("DELETE FROM Students WHERE StuNo = @StuNo",
                                new SqlParameter("@StuNo", stuNo));

                            DatabaseHelper.ExecuteNonQuery("DELETE FROM Users WHERE Username = @Username",
                                new SqlParameter("@Username", stuNo));

                            MessageBox.Show("学生删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            LoadStudents();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("删除失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请选择要删除的学生", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            };

            Button btnClose = new Button { Text = "关闭", Location = new Point(400, 420), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                searchPanel, dgvStudents,
                btnAdd, btnEdit, btnDelete, btnClose
            });
        }

        private void LoadStudents()
        {
            string searchKeyword = txtSearch.Text.Trim();
            string sql = "SELECT StuNo AS 学号, Name AS 姓名, Department AS 院系 FROM Students";

            if (!string.IsNullOrEmpty(searchKeyword))
            {
                sql += " WHERE StuNo LIKE @Keyword OR Name LIKE @Keyword OR Department LIKE @Keyword";
            }

            DataTable dt = DatabaseHelper.ExecuteQuery(sql,
                new SqlParameter("@Keyword", $"%{searchKeyword}%"));

            dgvStudents.DataSource = dt;
        }
    }

    // 编辑学生表单（保持不变）
    // ...

    public partial class EditStudentForm : Form
    {
        private string stuNo;

        public EditStudentForm(string stuNo)
        {
            this.stuNo = stuNo;
            InitializeComponent();
            LoadStudentData();
        }

        private void InitializeComponent()
        {
            // 窗体基本设置
            this.Text = "编辑学生信息";
            this.ClientSize = new Size(400, 250);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Font = new Font("Microsoft YaHei", 10F);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 学号标签和文本框
            Label lblStuNo = new Label
            {
                Text = "学号:",
                Location = new Point(30, 30),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtStuNo = new TextBox
            {
                Location = new Point(120, 30),
                Size = new Size(200, 30),
                ReadOnly = true,
                TabStop = false // 不可通过Tab键选中
            };

            // 姓名标签和文本框
            Label lblName = new Label
            {
                Text = "姓名:",
                Location = new Point(30, 80),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtName = new TextBox
            {
                Location = new Point(120, 80),
                Size = new Size(200, 30),
                MaxLength = 50 // 限制最大输入长度
            };

            // 院系标签和文本框
            Label lblDepartment = new Label
            {
                Text = "院系:",
                Location = new Point(30, 130),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtDepartment = new TextBox
            {
                Location = new Point(120, 130),
                Size = new Size(200, 30),
                MaxLength = 100
            };

            // 保存按钮
            Button btnSave = new Button
            {
                Text = "保存",
                Location = new Point(120, 180),
                Size = new Size(80, 35),
                DialogResult = DialogResult.OK
            };
            btnSave.Click += (sender, e) =>
            {
                string name = txtName.Text.Trim();
                string department = txtDepartment.Text.Trim();

                if (string.IsNullOrEmpty(name))
                {
                    MessageBox.Show("姓名不能为空", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtName.Focus();
                    return;
                }

                try
                {
                    DatabaseHelper.ExecuteNonQuery(
                        "UPDATE Students SET Name = @Name, Department = @Department WHERE StuNo = @StuNo",
                        new SqlParameter("@Name", name),
                        new SqlParameter("@Department", department),
                        new SqlParameter("@StuNo", stuNo));

                    MessageBox.Show("学生信息更新成功", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("更新学生信息失败: " + ex.Message, "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            // 取消按钮
            Button btnCancel = new Button
            {
                Text = "取消",
                Location = new Point(220, 180),
                Size = new Size(80, 35),
                DialogResult = DialogResult.Cancel
            };
            btnCancel.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
            lblStuNo, txtStuNo,
            lblName, txtName,
            lblDepartment, txtDepartment,
            btnSave, btnCancel
        });

            // 设置接受和取消按钮
            this.AcceptButton = btnSave;
            this.CancelButton = btnCancel;

            // 保存学号
            txtStuNo.Text = stuNo;
        }

        private void LoadStudentData()
        {
            try
            {
                DataTable dt = DatabaseHelper.ExecuteQuery(
                    "SELECT * FROM Students WHERE StuNo = @StuNo",
                    new SqlParameter("@StuNo", stuNo));

                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    foreach (Control ctrl in this.Controls)
                    {
                        if (ctrl is TextBox)
                        {
                            if (ctrl.Location.Y == 80) // 姓名文本框
                                ctrl.Text = row["Name"].ToString();
                            else if (ctrl.Location.Y == 130) // 院系文本框
                                ctrl.Text = row["Department"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载学生数据失败: " + ex.Message, "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    // 添加课程表单 - 添加年份字段
    public partial class AddCourseForm : Form
    {
        private TextBox txtYear;

        public AddCourseForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            // 窗体基本设置
            this.Text = "添加课程";
            this.ClientSize = new Size(400, 300);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Font = new Font("Microsoft YaHei", 10F);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 课程编号标签和文本框
            Label lblCourseNo = new Label
            {
                Text = "课程编号:",
                Location = new Point(30, 30),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtCourseNo = new TextBox
            {
                Location = new Point(120, 30),
                Size = new Size(200, 30)
            };

            // 课程名称标签和文本框
            Label lblCourseName = new Label
            {
                Text = "课程名称:",
                Location = new Point(30, 70),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtCourseName = new TextBox
            {
                Location = new Point(120, 70),
                Size = new Size(200, 30)
            };

            // 学分标签和文本框
            Label lblCredit = new Label
            {
                Text = "学分:",
                Location = new Point(30, 110),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            TextBox txtCredit = new TextBox
            {
                Location = new Point(120, 110),
                Size = new Size(200, 30)
            };

            // 年份标签和文本框
            Label lblYear = new Label
            {
                Text = "年份:",
                Location = new Point(30, 150),
                Size = new Size(80, 25),
                TextAlign = ContentAlignment.MiddleRight
            };

            txtYear = new TextBox
            {
                Location = new Point(120, 150),
                Size = new Size(200, 30),
                Text = DateTime.Now.Year.ToString()
            };

            // 保存按钮
            Button btnSave = new Button
            {
                Text = "保存",
                Location = new Point(120, 200),
                Size = new Size(80, 35)
            };

            btnSave.Click += (sender, e) =>
            {
                string courseNo = txtCourseNo.Text.Trim();
                string courseName = txtCourseName.Text.Trim();
                int credit;
                int year;

                if (string.IsNullOrEmpty(courseNo) || string.IsNullOrEmpty(courseName))
                {
                    MessageBox.Show("课程编号和课程名称不能为空", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(txtCredit.Text.Trim(), out credit))
                {
                    MessageBox.Show("学分必须为数字", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(txtYear.Text.Trim(), out year))
                {
                    MessageBox.Show("年份必须为数字", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    DatabaseHelper.ExecuteNonQuery(
                        "INSERT INTO Courses (CourseNo, CourseName, Credit, Year) VALUES (@CourseNo, @CourseName, @Credit, @Year)",
                        new SqlParameter("@CourseNo", courseNo),
                        new SqlParameter("@CourseName", courseName),
                        new SqlParameter("@Credit", credit),
                        new SqlParameter("@Year", year));

                    MessageBox.Show("课程添加成功", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("添加课程失败: " + ex.Message, "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            // 取消按钮
            Button btnCancel = new Button
            {
                Text = "取消",
                Location = new Point(220, 200),
                Size = new Size(80, 35)
            };

            btnCancel.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                lblCourseNo, txtCourseNo,
                lblCourseName, txtCourseName,
                lblCredit, txtCredit,
                lblYear, txtYear,
                btnSave, btnCancel
            });
        }
    }

    // 管理课程表单 - 添加模糊查询功能
    public partial class ManageCourseForm : Form
    {
        private DataGridView dgvCourses;
        private TextBox txtSearch;
        private Button btnSearch;

        public ManageCourseForm()
        {
            InitializeComponent();
            LoadCourses();
        }

        private void InitializeComponent()
        {
            this.Text = "管理课程";
            this.Size = new Size(700, 500);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 搜索面板
            Panel searchPanel = new Panel
            {
                Location = new Point(10, 10),
                Size = new Size(680, 40)
            };

            Label lblSearch = new Label { Text = "搜索:", Location = new Point(10, 10), AutoSize = true };
            txtSearch = new TextBox { Location = new Point(60, 10), Size = new Size(300, 25) };
            btnSearch = new Button { Text = "查询", Location = new Point(370, 10), Size = new Size(75, 25) };
            btnSearch.Click += (sender, e) => LoadCourses();

            searchPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, btnSearch });

            // 数据网格视图
            dgvCourses = new DataGridView
            {
                Location = new Point(10, 60),
                Size = new Size(680, 350),
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            // 按钮
            Button btnAdd = new Button { Text = "添加", Location = new Point(100, 420), Size = new Size(75, 30) };
            btnAdd.Click += (sender, e) => { new AddCourseForm().ShowDialog(); LoadCourses(); };

            Button btnEdit = new Button { Text = "编辑", Location = new Point(200, 420), Size = new Size(75, 30) };
            btnEdit.Click += (sender, e) =>
            {
                if (dgvCourses.SelectedRows.Count > 0)
                {
                    string courseNo = dgvCourses.SelectedRows[0].Cells["课程编号"].Value.ToString();
                    new EditCourseForm(courseNo).ShowDialog();
                    LoadCourses();
                }
                else
                {
                    MessageBox.Show("请选择要编辑的课程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            };

            Button btnDelete = new Button { Text = "删除", Location = new Point(300, 420), Size = new Size(75, 30) };
            btnDelete.Click += (sender, e) =>
            {
                if (dgvCourses.SelectedRows.Count > 0)
                {
                    string courseNo = dgvCourses.SelectedRows[0].Cells["课程编号"].Value.ToString();
                    string courseName = dgvCourses.SelectedRows[0].Cells["课程名称"].Value.ToString();

                    if (MessageBox.Show($"确定要删除课程 {courseName} 吗？", "确认",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        try
                        {
                            DatabaseHelper.ExecuteNonQuery("DELETE FROM Selections WHERE CourseNo = @CourseNo",
                                new SqlParameter("@CourseNo", courseNo));

                            DatabaseHelper.ExecuteNonQuery("DELETE FROM Courses WHERE CourseNo = @CourseNo",
                                new SqlParameter("@CourseNo", courseNo));

                            MessageBox.Show("课程删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            LoadCourses();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("删除失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请选择要删除的课程", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            };

            Button btnClose = new Button { Text = "关闭", Location = new Point(400, 420), Size = new Size(75, 30) };
            btnClose.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                searchPanel, dgvCourses,
                btnAdd, btnEdit, btnDelete, btnClose
            });
        }

        private void LoadCourses()
        {
            string searchKeyword = txtSearch.Text.Trim();
            string sql = "SELECT CourseNo AS 课程编号, CourseName AS 课程名称, Credit AS 学分, Year AS 年份 FROM Courses";

            if (!string.IsNullOrEmpty(searchKeyword))
            {
                sql += " WHERE CourseNo LIKE @Keyword OR CourseName LIKE @Keyword OR CAST(Year AS NVARCHAR) LIKE @Keyword";
            }

            DataTable dt = DatabaseHelper.ExecuteQuery(sql,
                new SqlParameter("@Keyword", $"%{searchKeyword}%"));

            dgvCourses.DataSource = dt;
        }
    }

    // 编辑课程表单 - 添加年份字段
    // 编辑课程表单
    public partial class EditCourseForm : Form
    {
        private string courseNo;
        // 声明类级别的文本框变量
        private TextBox txtCourseName;
        private TextBox txtCredit;
        private TextBox txtYear;

        public EditCourseForm(string courseNo)
        {
            this.courseNo = courseNo;
            InitializeComponent();
            LoadCourseData();
        }

        private void InitializeComponent()
        {
            //
            this.Text = "编辑课程";
            this.Size = new Size(300, 250);
            this.StartPosition = FormStartPosition.CenterScreen;

            // 课程编号
            Label lblCourseNo = new Label { Text = "课程编号:", Location = new Point(30, 30) };
            TextBox txtCourseNo = new TextBox { Location = new Point(100, 30), Size = new Size(150, 25), ReadOnly = true };


            // 课程名称
            Label lblCourseName = new Label { Text = "课程名称:", Location = new Point(30, 60) };
            // 直接赋值给类级别的变量
            txtCourseName = new TextBox { Location = new Point(100, 60), Size = new Size(150, 25) };

            // 学分
            Label lblCredit = new Label { Text = "学分:", Location = new Point(30, 90) };
            // 直接赋值给类级别的变量
            txtCredit = new TextBox { Location = new Point(100, 90), Size = new Size(150, 25) };

            // 年份
            Label lblYear = new Label { Text = "年份:", Location = new Point(30, 120) };
            // 直接赋值给类级别的变量
            txtYear = new TextBox { Location = new Point(100, 120), Size = new Size(150, 25) };

            // ... [其他初始化代码保持不变] ...
            // 保存按钮
            Button btnSave = new Button { Text = "保存", Location = new Point(60, 160), Size = new Size(75, 30) };
            btnSave.Click += (sender, e) =>
            {
                string courseName = txtCourseName.Text.Trim();
                int credit;
                int year;

                if (string.IsNullOrEmpty(courseName))
                {
                    MessageBox.Show("课程名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(txtCredit.Text.Trim(), out credit))
                {
                    MessageBox.Show("学分必须为数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!int.TryParse(txtYear.Text.Trim(), out year))
                {
                    MessageBox.Show("年份必须为数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {
                    DatabaseHelper.ExecuteNonQuery(
                        "UPDATE Courses SET CourseName = @CourseName, Credit = @Credit, Year = @Year WHERE CourseNo = @CourseNo",
                        new SqlParameter("@CourseName", courseName),
                        new SqlParameter("@Credit", credit),
                        new SqlParameter("@Year", year),
                        new SqlParameter("@CourseNo", courseNo));

                    MessageBox.Show("课程信息更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("更新课程信息失败: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            // 取消按钮
            Button btnCancel = new Button { Text = "取消", Location = new Point(140, 160), Size = new Size(75, 30) };
            btnCancel.Click += (sender, e) => this.Close();

            // 添加控件
            this.Controls.AddRange(new Control[] {
                lblCourseNo, txtCourseNo,
                lblCourseName, txtCourseName,
                lblCredit, txtCredit,
                lblYear, txtYear,
                btnSave, btnCancel
            });

            // 保存课程编号
            txtCourseNo.Text = courseNo;
        }

        private void LoadCourseData()
        {
            DataTable dt = DatabaseHelper.ExecuteQuery(
                "SELECT * FROM Courses WHERE CourseNo = @CourseNo",
                new SqlParameter("@CourseNo", courseNo));

            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                // 直接使用类级别的变量
                txtCourseName.Text = row["CourseName"].ToString();
                txtCredit.Text = row["Credit"].ToString();
                txtYear.Text = row["Year"].ToString();
            }
        }
    }
}

    // 主程序入口
    static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // 创建数据库表
        StudentCourseSystem.DatabaseHelper.CreateTables();

        Application.Run(new StudentCourseSystem.LoginForm());
    }
}